import { View, Text, Input, Button, Picker } from '@tarojs/components'
import { useState, useEffect } from 'react'
import Taro, { useLoad, useRouter } from '@tarojs/taro'
import './index.less'

export default function Booking() {
  const router = useRouter()
  const [bookingType, setBookingType] = useState('pickup') // pickup 或 store
  const [serviceType, setServiceType] = useState('wash')
  const [clothesCount, setClothesCount] = useState(1)
  const [address, setAddress] = useState('')
  const [contactName, setContactName] = useState('')
  const [contactPhone, setContactPhone] = useState('')
  const [appointmentDate, setAppointmentDate] = useState('')
  const [appointmentTime, setAppointmentTime] = useState('')
  const [selectedStore, setSelectedStore] = useState(0)
  const [userInfo, setUserInfo] = useState(null)
  const [loading, setLoading] = useState(false)

  // 服务类型配置
  const serviceTypes = [
    { value: 'wash', label: '普通洗涤', price: 15, icon: '🧺', desc: '适合日常衣物清洗' },
    { value: 'dry-clean', label: '干洗服务', price: 25, icon: '👔', desc: '适合西装、大衣等' },
    { value: 'repair', label: '修补服务', price: 30, icon: '🪡', desc: '衣物修补、改制' }
  ]

  // 门店列表
  const stores = [
    { name: '捷净洗护(三里屯店)', address: '北京市朝阳区三里屯SOHO', phone: '010-12345678' },
    { name: '捷净洗护(国贸店)', address: '北京市朝阳区国贸中心', phone: '010-87654321' },
    { name: '捷净洗护(中关村店)', address: '北京市海淀区中关村大街', phone: '010-11223344' }
  ]

  // 时间选择器数据
  const timeSlots = [
    '09:00', '10:00', '11:00', '14:00', '15:00', '16:00', '17:00', '18:00'
  ]

  useLoad(() => {
    // 获取路由参数
    const { type } = router.params
    if (type) {
      setBookingType(type)
    }

    // 检查登录状态
    checkLogin()
    
    // 设置默认预约时间为明天
    const tomorrow = new Date()
    tomorrow.setDate(tomorrow.getDate() + 1)
    setAppointmentDate(tomorrow.toISOString().split('T')[0])
    setAppointmentTime('09:00')
  })

  const checkLogin = () => {
    try {
      const user = Taro.getStorageSync('userInfo')
      if (!user) {
        Taro.showModal({
          title: '提示',
          content: '请先登录后再预约服务',
          success: (res) => {
            if (res.confirm) {
              Taro.navigateTo({ url: '/pages/login/index' })
            } else {
              Taro.navigateBack()
            }
          }
        })
        return
      }
      setUserInfo(user)
      setContactName(user.nickname || '')
      setContactPhone(user.phone || '')
    } catch (error) {
      console.log('获取用户信息失败')
    }
  }

  const getCurrentService = () => {
    return serviceTypes.find(service => service.value === serviceType)
  }

  const calculateTotalPrice = () => {
    const service = getCurrentService()
    const basePrice = service ? service.price * clothesCount : 0
    
    // 会员折扣
    const discount = userInfo?.isMember ? 0.9 : 1
    return Math.round(basePrice * discount)
  }

  const generatePickupCode = () => {
    return Math.floor(100000 + Math.random() * 900000).toString()
  }

  const handleSubmit = async () => {
    // 表单验证
    if (!contactName.trim()) {
      Taro.showToast({ title: '请输入联系人姓名', icon: 'none' })
      return
    }

    if (!contactPhone.trim()) {
      Taro.showToast({ title: '请输入联系电话', icon: 'none' })
      return
    }

    if (!/^1[3-9]\d{9}$/.test(contactPhone)) {
      Taro.showToast({ title: '请输入正确的手机号', icon: 'none' })
      return
    }

    if (bookingType === 'pickup' && !address.trim()) {
      Taro.showToast({ title: '请输入取件地址', icon: 'none' })
      return
    }

    if (!appointmentDate) {
      Taro.showToast({ title: '请选择预约日期', icon: 'none' })
      return
    }

    if (!appointmentTime) {
      Taro.showToast({ title: '请选择预约时间', icon: 'none' })
      return
    }

    setLoading(true)

    try {
      // 模拟提交请求
      await new Promise(resolve => setTimeout(resolve, 2000))

      // 创建订单
      const order = {
        id: `JJ${Date.now()}`,
        type: bookingType,
        serviceType: serviceType,
        clothesCount: clothesCount,
        price: calculateTotalPrice(),
        address: bookingType === 'pickup' ? address : stores[selectedStore].name,
        contactName: contactName,
        contactPhone: contactPhone,
        createTime: new Date().toLocaleString(),
        appointmentTime: `${appointmentDate} ${appointmentTime}`,
        status: 'pending',
        pickupCode: generatePickupCode()
      }

      // 保存订单
      const existingOrders = Taro.getStorageSync('orders') || []
      existingOrders.unshift(order)
      Taro.setStorageSync('orders', existingOrders)

      Taro.showToast({
        title: '预约成功！',
        icon: 'success'
      })

      setTimeout(() => {
        Taro.navigateTo({
          url: `/pages/order-detail/index?id=${order.id}`
        })
      }, 1500)

    } catch (error) {
      Taro.showToast({
        title: '预约失败，请重试',
        icon: 'none'
      })
    } finally {
      setLoading(false)
    }
  }

  const handleDateChange = (e) => {
    setAppointmentDate(e.detail.value)
  }

  const handleTimeChange = (e) => {
    setAppointmentTime(timeSlots[e.detail.value])
  }

  const handleStoreChange = (e) => {
    setSelectedStore(e.detail.value)
  }

  return (
    <View className='booking-page'>
      {/* 服务类型选择 */}
      <View className='section-card'>
        <View className='section-title'>
          <Text className='title-icon'>🛍️</Text>
          <Text className='title-text'>选择服务类型</Text>
        </View>
        
        <View className='service-types'>
          {serviceTypes.map(service => (
            <View 
              key={service.value}
              className={`service-item ${serviceType === service.value ? 'active' : ''}`}
              onClick={() => setServiceType(service.value)}
            >
              <View className='service-icon'>{service.icon}</View>
              <View className='service-info'>
                <Text className='service-name'>{service.label}</Text>
                <Text className='service-desc'>{service.desc}</Text>
                <Text className='service-price'>¥{service.price}/件</Text>
              </View>
              <View className='service-radio'>
                {serviceType === service.value && <Text className='radio-checked'>✓</Text>}
              </View>
            </View>
          ))}
        </View>
      </View>

      {/* 预约方式选择 */}
      <View className='section-card'>
        <View className='section-title'>
          <Text className='title-icon'>📍</Text>
          <Text className='title-text'>选择预约方式</Text>
        </View>
        
        <View className='booking-types'>
          <View 
            className={`booking-type ${bookingType === 'pickup' ? 'active' : ''}`}
            onClick={() => setBookingType('pickup')}
          >
            <View className='type-icon'>🚚</View>
            <Text className='type-text'>上门取件</Text>
            <Text className='type-desc'>师傅上门取件</Text>
          </View>
          
          <View 
            className={`booking-type ${bookingType === 'store' ? 'active' : ''}`}
            onClick={() => setBookingType('store')}
          >
            <View className='type-icon'>🏪</View>
            <Text className='type-text'>到店取件</Text>
            <Text className='type-desc'>自行送到门店</Text>
          </View>
        </View>
      </View>

      {/* 衣物数量 */}
      <View className='section-card'>
        <View className='section-title'>
          <Text className='title-icon'>👕</Text>
          <Text className='title-text'>衣物数量</Text>
        </View>
        
        <View className='clothes-counter'>
          <Button 
            size='mini'
            className='counter-btn'
            disabled={clothesCount <= 1}
            onClick={() => setClothesCount(Math.max(1, clothesCount - 1))}
          >
            -
          </Button>
          <Text className='counter-value'>{clothesCount}</Text>
          <Button 
            size='mini'
            className='counter-btn'
            onClick={() => setClothesCount(clothesCount + 1)}
          >
            +
          </Button>
        </View>
      </View>

      {/* 地址信息 */}
      {bookingType === 'pickup' ? (
        <View className='section-card'>
          <View className='section-title'>
            <Text className='title-icon'>🏠</Text>
            <Text className='title-text'>取件地址</Text>
          </View>
          
          <View className='form-item'>
            <Input
              placeholder='请输入详细地址'
              value={address}
              onInput={(e) => setAddress(e.detail.value)}
              className='address-input'
            />
          </View>
        </View>
      ) : (
        <View className='section-card'>
          <View className='section-title'>
            <Text className='title-icon'>🏪</Text>
            <Text className='title-text'>选择门店</Text>
          </View>
          
          <Picker 
            mode='selector'
            range={stores.map(store => store.name)}
            value={selectedStore}
            onChange={handleStoreChange}
          >
            <View className='store-picker'>
              <Text className='picker-text'>{stores[selectedStore].name}</Text>
              <Text className='picker-arrow'>▼</Text>
            </View>
          </Picker>
          
          <View className='store-info'>
            <Text className='store-address'>📍 {stores[selectedStore].address}</Text>
            <Text className='store-phone'>📞 {stores[selectedStore].phone}</Text>
          </View>
        </View>
      )}

      {/* 联系信息 */}
      <View className='section-card'>
        <View className='section-title'>
          <Text className='title-icon'>👤</Text>
          <Text className='title-text'>联系信息</Text>
        </View>
        
        <View className='form-group'>
          <View className='form-item'>
            <Text className='form-label'>联系人</Text>
            <Input
              placeholder='请输入联系人姓名'
              value={contactName}
              onInput={(e) => setContactName(e.detail.value)}
              className='form-input'
            />
          </View>
          
          <View className='form-item'>
            <Text className='form-label'>联系电话</Text>
            <Input
              type='number'
              placeholder='请输入联系电话'
              value={contactPhone}
              onInput={(e) => setContactPhone(e.detail.value)}
              className='form-input'
            />
          </View>
        </View>
      </View>

      {/* 预约时间 */}
      <View className='section-card'>
        <View className='section-title'>
          <Text className='title-icon'>⏰</Text>
          <Text className='title-text'>预约时间</Text>
        </View>
        
        <View className='time-group'>
          <View className='time-item'>
            <Text className='time-label'>预约日期</Text>
            <Picker
              mode='date'
              value={appointmentDate}
              start={new Date().toISOString().split('T')[0]}
              onChange={handleDateChange}
            >
              <View className='time-picker'>
                <Text className='picker-text'>{appointmentDate || '请选择日期'}</Text>
                <Text className='picker-arrow'>▼</Text>
              </View>
            </Picker>
          </View>
          
          <View className='time-item'>
            <Text className='time-label'>预约时间</Text>
            <Picker
              mode='selector'
              range={timeSlots}
              value={timeSlots.indexOf(appointmentTime)}
              onChange={handleTimeChange}
            >
              <View className='time-picker'>
                <Text className='picker-text'>{appointmentTime || '请选择时间'}</Text>
                <Text className='picker-arrow'>▼</Text>
              </View>
            </Picker>
          </View>
        </View>
      </View>

      {/* 价格计算 */}
      <View className='price-card'>
        <View className='price-row'>
          <Text className='price-label'>服务费用</Text>
          <Text className='price-value'>¥{getCurrentService()?.price || 0} × {clothesCount}件</Text>
        </View>
        
        {userInfo?.isMember && (
          <View className='price-row discount'>
            <Text className='price-label'>会员折扣</Text>
            <Text className='price-value'>-¥{Math.round((getCurrentService()?.price || 0) * clothesCount * 0.1)}</Text>
          </View>
        )}
        
        <View className='price-divider'></View>
        
        <View className='price-row total'>
          <Text className='price-label'>合计金额</Text>
          <Text className='price-total'>¥{calculateTotalPrice()}</Text>
        </View>
      </View>

      {/* 提交按钮 */}
      <View className='submit-section'>
        <Button
          type='primary'
          loading={loading}
          onClick={handleSubmit}
          className='submit-btn'
        >
          {loading ? '提交中...' : '确认预约'}
        </Button>
        
        <View className='submit-tips'>
          <Text className='tips-text'>
            预约成功后，我们会在预约时间前30分钟联系您确认
          </Text>
        </View>
      </View>
    </View>
  )
}